//
//  WHRAgriculturalCapitalClassifyVC.m
//  AnXin100
//
//  Created by 天质弘耕 on 2018/12/4.
//  Copyright © 2018 tzhg. All rights reserved.
//农资分类

#import "WHRAgriculturalCapitalClassifyVC.h"
#import "JKAreaCollectionViewCell.h"
#import "JKAreaTableViewCell.h"
#import "JKReusableView.h"
#import "FootReusableView.h"
#import "JKFlowLayout.h"
#import "UIViewController+HBD.h"
#import "LLSearchViewController.h"
#import "AXYjsgViewController.h"

@interface WHRAgriculturalCapitalClassifyVC  ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    JKFlowLayout *layout;
    NSInteger _selectIndex;//记录位置
    BOOL _isScrollDown;//滚动方向
}
/** 一级标题 左边的分类 */
@property(nonatomic,strong) NSMutableArray *tableTittleDataArray;
/** 二级标题 collectionview上面的标题 */
@property(nonatomic,strong) NSMutableArray *headTittleDataArray;
/** 三级标题 collectionviewCell的标题 */
@property(nonatomic,strong) NSMutableArray *dataArray;

@property(nonatomic,strong) UICollectionView *collectionView;
/** 产品图片 */
@property (nonatomic , strong) NSArray<NSString *> *images;

@property(nonatomic,strong)UITableView *tableView;

@end

@implementation WHRAgriculturalCapitalClassifyVC

static NSString *cellID = @"cellID";
static NSString *headerID = @"headerID";
static NSString *footerID = @"footerID";

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigationItems];
    
    self.view.backgroundColor = backgrCOlor;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.images = @[@"ls",@"sc",@"sg",@"sx",@"ls",@"sc",@"sg",@"sx",@"sg",@"sx"];
    /** 导航条白色 */
    self.hbd_barTintColor = [UIColor whiteColor];
    self.hbd_barShadowHidden = YES;
    /** 去掉导航条下面的线*/
    self.hbd_barShadowHidden = YES;
    
    _selectIndex = 0;
    _isScrollDown = YES;
    
    /** 一级标题 */
    [self.tableTittleDataArray addObjectsFromArray:@[@"种子",@"农药",@"肥料",@"农机具",@"水果",@"蔬菜",@"专落实",@"生菜",@"农药",@"米饭"]];
    /** 二级标题 */
    [self.headTittleDataArray addObjectsFromArray:@[@"绿植园艺",@"热卖推荐",@"种子",@"农药",@"肥料",@"饲料",@"专兽药",@"腰肢器具",@"农业器具",@"园艺"]];
    /** 三级标题 */
    [self.dataArray addObjectsFromArray:  @[@[@"葡萄",@"香蕉",@"米饭",@"橘子",@"蔬菜",@"洋芋",@"花卉"],@[@"葡萄",@"香蕉",@"米饭",@"橘子"],@[@"葡萄",@"香蕉",@"米饭",@"橘子"],@[@"香蕉"],@[@"橘子"],@[@"d橙子"],@[@"栗子"],@[@"香蕉"],@[@"葡萄",@"香蕉",@"米饭",@"橘子",@"蔬菜",@"洋芋",@"花卉"],@[@"葡萄",@"香蕉",@"米饭",@"橘子",@"蔬菜",@"洋芋",@"花卉"]]];
    
    layout = [JKFlowLayout new];
    //layout.itemSize = CGSizeMake((CIO_SCREEN_WIDTH-78)/4.0, 40);
    //layout.sectionInset = UIEdgeInsetsMake(1, 0, 1, 0);
    layout.naviHeight = 0;
    
    /**
     *  设置滑动方向
     *  UICollectionViewScrollDirectionHorizontal 水平方向
     *  UICollectionViewScrollDirectionVertical   垂直方向
     */
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    [self.collectionView registerClass:[JKAreaCollectionViewCell class] forCellWithReuseIdentifier:cellID];
    [self.collectionView registerClass:[JKReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader  withReuseIdentifier:headerID];
    [self.collectionView registerClass:[FootReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter  withReuseIdentifier:footerID];
    
    // collectionView 的添加
    [self.view addSubview:self.collectionView];
    
    // tableView 的添加
    [self.view addSubview:self.tableView];
    UIView *headTableView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,  SCREEN_WIDTH, 8)];
    headTableView.backgroundColor = backgrCOlor;
    self.tableView.tableHeaderView = headTableView;
}

#pragma mark - action

//自定义UIBarButtonItem
- (void)setupNavigationItems {
    
    /** 导航条左边的按钮 */
    //返回按钮
    UIButton *kfBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [kfBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    kfBtn.frame = CGRectMake(0, 0, 60, 30);
    [kfBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:kfBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    /** 搜索 */
    
    UIButton *searchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-140, 30)];
    searchButton.backgroundColor = [UIColor whiteColor];
    searchButton.titleLabel.font = FONT_TWELVE;
    [searchButton addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    [searchButton setTitleColor:[UIColor colorWithHex:0x29b566] forState:UIControlStateNormal];
    [searchButton setTitle:@"农资分类" forState:UIControlStateNormal];
    searchButton.cornerRadius = 15;
    [searchButton setImage:[UIImage imageNamed:@"ss"] forState:UIControlStateNormal];
    self.navigationItem.titleView = searchButton;
    
    
    
}

#pragma mark - Action

/** 搜索 */
- (void)search:(UIButton *)btu {
    
    LLSearchViewController *vc = [[LLSearchViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)backAction:(UIBarButtonItem *)item {
    
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - collectionViewDelegate & datasource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.headTittleDataArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *array = self.dataArray[section];
    return array.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    JKAreaCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.areaImageView.image = [UIImage imageNamed:self.images[indexPath.row]];
    NSArray *array = self.dataArray[indexPath.section];
    cell.areaName.text = array[indexPath.row];
    
    return cell;
    
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (kind==UICollectionElementKindSectionFooter) {
        
        FootReusableView *footer = [collectionView  dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerID forIndexPath:indexPath];
        footer.backgroundColor = backgrCOlor;
        return footer;
    }
    
    JKReusableView *header = [collectionView  dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerID forIndexPath:indexPath];
    header.backgroundColor = [UIColor whiteColor];
    header.headText.text = [NSString stringWithFormat:@"%@",self.headTittleDataArray[indexPath.section]];
    
    
    return header;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    
    
    return CGSizeMake(0, 40);
    
    // return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    
    
    return CGSizeMake(0, 8);
}

// 导航栏是否消失
-(BOOL)prefersStatusBarHidden
{
    return NO;
}

//列间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 1.f;
}

//行间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 1.f;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(1, 0, 1,0);
}
/*
 格子的宽高设置
 */
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((SCREEN_WIDTH-89-9-2)/3.0, ((SCREEN_WIDTH-89-9-2)/3.0/4)*3+40);
}
-(UICollectionView *)collectionView{
    
    if (!_collectionView) {
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(89,8, SCREEN_WIDTH-89-9, SCREEN_HEIGHT-64-8) collectionViewLayout: layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceVertical = NO;
        _collectionView.alwaysBounceHorizontal = NO;
        _collectionView.pagingEnabled = NO;
    }
    
    return _collectionView;
}

-(NSMutableArray *)dataArray{
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc]init];
    }
    
    return _dataArray;
}

-(NSMutableArray *)headTittleDataArray{
    
    if (!_headTittleDataArray) {
        _headTittleDataArray = [[NSMutableArray alloc]init];
    }
    return _headTittleDataArray;
}



-(NSMutableArray *)tableTittleDataArray{
    
    if (!_tableTittleDataArray) {
        _tableTittleDataArray = [[NSMutableArray alloc]init];
    }
    return _tableTittleDataArray;
}


-(UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, 88, SCREEN_HEIGHT-64)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //self.tableView.bounces = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor  = backgrCOlor;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    
    return _tableView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.tableTittleDataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"cellID";
    
    JKAreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        
        cell = [[JKAreaTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (_selectIndex == indexPath.row) {
        
        cell.nameText.backgroundColor = [UIColor whiteColor];
    }else{
        cell.nameText.backgroundColor = whitesmallColorc;
    }
    
    cell.nameText.text = self.tableTittleDataArray[indexPath.row];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 40;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.1)];
    headView.backgroundColor = backgrCOlor;
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.1f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,  SCREEN_WIDTH, 0.1)];
    footView.backgroundColor = backgrCOlor;
    
    return footView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.1f;
}

// CollectionView分区标题即将展示
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    //         当前CollectionView滚动的方向向上，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
    if (!_isScrollDown && (collectionView.dragging || collectionView.decelerating)) {
        [self selectRowAtIndexPath:indexPath.section];
    }
}
// CollectionView分区标题展示结束
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(nonnull UICollectionReusableView *)view forElementOfKind:(nonnull NSString *)elementKind atIndexPath:(nonnull NSIndexPath *)indexPath {
    //当前CollectionView滚动的方向向下，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
    if (_isScrollDown && (collectionView.dragging || collectionView.decelerating)) {
        [self selectRowAtIndexPath:indexPath.section + 1];
    }
}
// 当拖动CollectionView的时候，处理TableView
- (void)selectRowAtIndexPath:(NSInteger)index {
    
    _selectIndex = index;
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    [self.tableView reloadData];
}

#pragma mark - UIScrollView Delegate
// 标记一下CollectionView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    static float lastOffsetY = 0;
    if (self.collectionView == scrollView) {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

// 选中 处理collectionView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _selectIndex = indexPath.row;
    CGRect headerRect = [self frameForHeaderForSection:_selectIndex];
    CGPoint topOfHeader = CGPointMake(0, headerRect.origin.y - _collectionView.contentInset.top);
    [self.collectionView setContentOffset:topOfHeader animated:YES];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [self.tableView reloadData];
}

- (CGRect)frameForHeaderForSection:(NSInteger)section {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:section];
    UICollectionViewLayoutAttributes *attributes = [self.collectionView.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
    return attributes.frame;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    AXYjsgViewController *vc = [AXYjsgViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)click{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}



@end


